package com.jianggy.redis.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.TimeUnit;


/**
 * Hello world!
 */
public class JedisApp {
    private static final String REDIS_URL = "192.168.231.6";
    private static final int REDIS_PORT = 6379;

    public static void main(String[] args) {
        // jedisTest();
        jedisPoolTest();
    }

    /**
     * 建立单个连接，类似数据库的connection
     * @author jianggy
     * @time 2018/12/19 10:10
     */
    public static void jedisTest() {
        Jedis jedis = new Jedis(REDIS_URL);
        jedis.select(1);
        String value = jedis.get("abc");
        System.out.println(value);
        jedis.close();
    }
    /**
     * 通过连接池的方式连接redis
     * @author jianggy
     * @time 2018/12/19 11:08
     */
    public static void jedisPoolTest() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(5);
        config.setMaxIdle(3);
        config.setMaxWaitMillis(10000);
        config.setTestOnBorrow(false);
        config.setMinIdle(3);
        JedisPool pool = new JedisPool(config, REDIS_URL, REDIS_PORT);
        for (int i = 0; i < 10; i++) {
            System.out.println("开始第" + i + "次");
            try {
                TimeUnit.SECONDS.sleep(2);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            Jedis jedis = pool.getResource();
            jedis.select(1);
            String value = jedis.get("abc");
            System.out.println("abc的值为：" + value+",活跃的连接数量为："+pool.getNumActive());
            jedis.close();
        }
    }
}
